<template>
    <Layout>
        <Form ref="form1" :model="form1" :label-width="120">
            <Row class="query-form" style="padding-top: 15px">
                <Col span="8">
                    <FormItem label="所属单位：" prop="belongOrgId">
                        <cascaderDom class="query-form-el" ref="childConOrg" @setOrgInfo="setQueryOrgId"
                                     @setOrgname="setQueryOrgName" :currentOrgId="currentOrgId"
                                     :currentOrgName="currentOrgName" :orgTree="true"></cascaderDom>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="模板名称：" prop="modelName">
                        <Input class="query-form-el" type="text" v-model="form1.modelName"/>
                    </FormItem>
                </Col>
                <Col span="8">
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                </Col>
            </Row>
            <Row class="query-form">
                <Col span="24">
                    <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
                    <!--<Button size="large" class="ivu-btn-delete" icon="md-trash" @click="batDelete">删除</Button>-->
                </Col>
            </Row>
        </Form>
        <Table ref='table' :height="tableHeight" size="small" :loading="loading" class="table" no-data-text="没有查询到相关数据!"
               highlight-row stripe border :columns="columns1" width="100%" :data="dataTable">
        </Table>

        <Row style="margin-right:10px;">
            <Col span="24">
                <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
                      @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
                      show-total show-sizer show-elevator/>
            </Col>
        </Row>
        <modelInfo ref="child" :model1="model1" :form1data="InputData" :form1datacopy="InputData"
                   @addOrUpdateData="addOrUpdateData">
        </modelInfo>

        <Modal title="模板详情" :transfer=false v-model="model4" :width=900>
            <Form :label-width="100">
            <Row>
                <Col span="24">
                    <Table  :loading="loading"  size="small" :columns="pointColumns" :data="pointData" ></Table>
                </Col>
            </Row>
            </Form>
            <div slot="footer">
                <Button class='ivu-btn-save' @click="model4=false">关闭</Button>
            </div>
        </Modal>
    </layout>
</template>

<script>
    import {Api} from '../../../../api/index.js'
    import modelInfo from './modelInfo.vue'
    import cascaderDom from "../../../../components/cascader-dom.vue"
    import {sessionStorage} from '../../../../common/cacheUtils.js';
    import '@riophae/vue-treeselect/dist/vue-treeselect.css'

    export default {
        components: {
            modelInfo, cascaderDom
        },
        data() {
            return {
                switchFlag: false,
                form1: {},
                //分页参数
                pageSizeArray: [10, 20, 50],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                },
                columns1: [
                    {
                        title: "序号",
                        width: 80,
                        align: "center",
                        fixed: 'left',
                        render: (h, params) => {
                            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
                        }
                    },
                    {
                        width: 300,
                        minWidth: 100,
                        title: '模板名称',
                        key: 'modelName',
                        align: 'center'
                    },
                    {
                        minWidth: 150,
                        title: '所属单位',
                        align: 'center',
                        key: 'orgName'
                    },
                    {
                        minWidth: 110,
                        title: '模板类型',
                        key: 'modelTypeName',
                        align: 'center'
                    },
                    {
                        minWidth: 100,
                        title: '创建人',
                        key: 'createUserName',
                        align: 'center'
                    },
                    {
                        minWidth: 120,
                        title: '创建时间',
                        key: 'createDate',
                        align: 'center'
                    },
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        width: 230,
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {fontSize: '14px',
                                        color: params.row.createUserId == sessionStorage('userId').getObject('userId').userId ||  this.Common.userIdList.includes(sessionStorage('userId').getObject('userId').userId ) ? '':'#d0d0d0' ,
                                        pointerEvents: params.row.createUserId == sessionStorage('userId').getObject('userId').userId ||  this.Common.userIdList.includes(sessionStorage('userId').getObject('userId').userId ) ? '' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.editItems(params);
                                        }
                                    }
                                }, '模板配置'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                        click: () => {
                                            this.viewDate(params.row);
                                            // this.showData(params, 1);
                                        }
                                    }
                                }, '详情'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: params.row.createUserId == sessionStorage('userId').getObject('userId').userId ||  this.Common.userIdList.includes(sessionStorage('userId').getObject('userId').userId ) ||sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                                        ||sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined? '':'#d0d0d0' ,
                                        pointerEvents: params.row.createUserId == sessionStorage('userId').getObject('userId').userId ||  this.Common.userIdList.includes(sessionStorage('userId').getObject('userId').userId )||sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                                        ||sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined? '' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.showData(params, 2);
                                        }
                                    }
                                }, '修改'), h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: params.row.createUserId == sessionStorage('userId').getObject('userId').userId ||  this.Common.userIdList.includes(sessionStorage('userId').getObject('userId').userId )||sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                                        ||sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined? 'red':'#d0d0d0' ,
                                        pointerEvents: params.row.createUserId == sessionStorage('userId').getObject('userId').userId ||  this.Common.userIdList.includes(sessionStorage('userId').getObject('userId').userId ) ||sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                                        ||sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined? '' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.deleteData(params);
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    }
                ],
                currentOrgId: '',
                currentOrgName: '',
                specialtyData: [],
                modelTypeData: [],
                dataTable: [],
                InputData: {},
                model1: false,
                add: false,
                tableHeight: '',
                loading: false,
                deleteRows: [],

                pointData:[],
                pointColumns:[],
                datas:[],
                listData:[],
                model4:false,
            }
        },
        mounted: function () {
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
            this.selectCodingSort();
            this.query();
        },
        methods: {
            selectCodingSort() {
                this.$http.get(Api.queryCodeDetailBySortId + '/1000001012', {params: {}}).then((res) => {
                    this.specialtyData = [];
                    res.data.data.map(item => {
                        let obj = {};
                        obj.id = item.codingCodeId;
                        obj.label = item.codingName;
                        obj.children = null;
                        this.specialtyData.push(obj);
                    });
                })
                this.$http.get(Api.queryCodeDetailBySortId + '/1000001011', {params: {}}).then((res) => {
                    this.modelTypeData = [];
                    res.data.data.map(item => {
                        let obj = {};
                        obj.id = item.codingCodeId;
                        obj.label = item.codingName;
                        obj.children = null;
                        this.modelTypeData.push(obj);
                    });
                })

            },
            editItems(params) {
                this.$router.push({name: 'checkItemsInfo', params: {'data': params.row}});
            },
            addInfo() {
                this.model1 = true;
                this.$refs.child.form1datacopy = {};
                this.$refs.child.isdisabledFn = false;
                this.$refs.child.showSaveBtn = true;
                this.$refs.child.form1datacopy.modelId = '';
                this.$refs.child.form1datacopy.belongOrgId = JSON.parse(sessionStorage('userId').get('userId')).companyId;

                // this.$refs.child.currentOrgId = JSON.parse(sessionStorage('paramUserInfo').get('userInfo'))["createOrgId"];
                // this.$refs.child.currentOrgName = JSON.parse(sessionStorage('paramUserInfo').get('userInfo'))["createOrgName"];
                this.$refs.child.currentOrgId = JSON.parse(sessionStorage('userId').get('userId')).companyId;
                this.$refs.child.currentOrgName = JSON.parse(sessionStorage('userId').get('userId')).companyName;
                setTimeout(() => {
                    this.$refs.child.$refs.childConOrg.setCurrentOrg();
                }, 100);
                this.$refs.child.$refs.form1datacopy.resetFields();

            },
            addModalStaFun(status) {
                this.model1 = status;
            },
            getSelectRows(rows) {
                this.deleteRows = rows;
            },
            setQueryOrgId(data) {
                this.form1.belongOrgId = data[data.length - 1];
            },
            setQueryOrgName(data) {
                this.form1.belongOrgName = data;
            },
            pageChange(pageNum) {
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            pageSizeChange(pageSize) {
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            deleteData(params) {
                this.$Modal.confirm({
                    title: '提示',
                    content: '<p>确认删除此行数据？</p>',
                    onOk: () => {
                        let url = Api.deleteModel;
                        this.$http.get(url, {params: {modelId: params.row.modelId}}).then((res) => {
                            this.$Message.success('删除成功');
                            this.query()
                        }).catch(e => {
                            this.$Message.error('请求失败' + e);
                        })
                    },
                    onCancel: () => {
                    }
                });
            },
            viewDate(row){
                let _this = this;
                let parentId= ""
                let url=Api.getListItemByParentId
                this.$http.get(url + "?parentId="+parentId+"&modelVersionId="+row.modelVersionId).then((res) => {
                    if(res.data!=null){
                        console.log(res.data)
                        // _this.listData=res.data
                            _this.pointData = [];
                            _this.datas = [];
                            _this.pointColumns = [];
                            //列表项
                            _this.findAllItem(res.data);
                            //列表项最大深度
                            let maxDeep = 0;
                            _this.datas.forEach((item,index)=>{
                                let obj = {};
                                //获取列表项所有父级的name依次展示在table里
                                let names = item.itemName.split('|&|');
                                let writeDesc = item.writeDesc&&item.writeDesc.split('|&|');
                                    for(let i = 0; i<names.length ; i++){
                                    obj['listName' + i] = names[i];
                                    obj['writeDesc' + i] = writeDesc==null||writeDesc[i]==null?'':writeDesc[i];
                                }

                                let tempMaxDeep = names.length;
                                if(tempMaxDeep > maxDeep){
                                    maxDeep = tempMaxDeep;
                                }
                                obj.listItemId = item.listItemId;
                                _this.pointData.push(obj);
                            })
                            //列表项表头
                            for(let i = 0; i <maxDeep; i++ ){
                                debugger
                                let tableTitle = {};
                                tableTitle = {
                                    minWidth: 150,
                                    title: '检查项目',
                                    key: 'listName' + i,
                                    align: 'left',
                                };
                                _this.pointColumns.push(tableTitle);
                                // let tableTitle1 = {};
                                // tableTitle1 = {
                                //     minWidth: 150,
                                //     title: '检查内容',
                                //     key: 'writeDesc' + i,
                                //     align: 'left',tooltip:true
                                // };
                                // _this.pointColumns.push(tableTitle1);
                            }
                            _this.model4=true
                    }
                    console.log(_this.listData)
                }, function () {
                    _this.$Message.info('获取机构信息失败');
                });
            },
            /*viewDate(row){
                let _this = this;
                _this.viewDate1(row)
                setTimeout(() =>{
                    _this.pointData = [];
                    _this.datas = [];
                    _this.pointColumns = [];
                    //列表项
                    _this.findAllItem(_this.listData);
                    //console.log(_this.datas);
                    //列表项最大深度
                    let maxDeep = 0;
                    _this.datas.forEach((item,index)=>{
                        let obj = {};
                        //获取列表项所有父级的name依次展示在table里
                        let names = item.itemName.split('|&|');
                        // let writeDesc = item.writeDesc&&item.writeDesc.split('|&|');
                        for(let i = 0; i<names.length ; i++){
                            obj['listName' + i] = names[i];
                            // obj['writeDesc' + i] = writeDesc==null||writeDesc[i]==null?'':writeDesc[i];
                        }

                        let tempMaxDeep = names.length;
                        if(tempMaxDeep > maxDeep){
                            maxDeep = tempMaxDeep;
                        }
                        obj.listItemId = item.listItemId;
                        _this.pointData.push(obj);
                    })
                    //列表项表头
                    for(let i = 0; i <maxDeep; i++ ){
                        debugger
                        let tableTitle = {};
                        tableTitle = {
                            minWidth: 150,
                            title: '检查项目',
                            key: 'listName' + i,
                            align: 'left',
                        };
                        _this.pointColumns.push(tableTitle);
                        // let tableTitle1 = {};
                        // tableTitle1 = {
                        //     minWidth: 150,
                        //     title: '检查内容',
                        //     key: 'writeDesc' + i,
                        //     align: 'left',tooltip:true
                        // };
                        // _this.pointColumns.push(tableTitle1);
                    }
                    _this.model4=true
                },2000);
            },*/
            findAllItem(listItem){
                let _this=this
                listItem.forEach((item,index)=>{
                    if(item.children!=null && item.children!=undefined){
                        if(item.children.length > 0){
                            _this.findAllItem(item.children);
                        }else{
                            _this.datas.push(item);
                        }
                    }else{
                        _this.datas.push(item);
                    }
                })
            },
            showData(params, optType) {
                let url = Api.getModelById + params.row.modelId;
                this.$http.get(url, {}).then((res) => {
                    this.InputData = res.data.model;

                    this.$refs.child.form1datacopy.modelId = this.InputData.modelId;
                    this.$refs.child.form1datacopy.modelName = this.InputData.modelName;
                    this.$refs.child.form1datacopy.abbrName = this.InputData.abbrName;
                    this.$refs.child.form1datacopy.ifOpenGps = this.InputData.ifOpenGps;
                    this.$refs.child.form1datacopy.modelDesc = this.InputData.modelDesc;
                    this.$refs.child.form1datacopy.applyUnit = this.InputData.applyUnit
                    this.$refs.child.currentOrgId = this.InputData.belongOrgId;
                    this.$refs.child.currentOrgName = this.InputData.belongOrgName;
                    this.$refs.child.form1datacopy.modelUserId = this.InputData.modelUser;
                    this.$refs.child.form1datacopy.specialty = this.InputData.specialty;
                    this.$refs.child.form1datacopy.modelType = this.InputData.modelType;
                    this.$refs.child.form1datacopy.modelBusiness = this.InputData.modelBusiness;


                    if (optType == '1') {
                        this.$refs.child.isdisabledFn = true;
                        this.$refs.child.showSaveBtn = false;
                        this.$refs.child.modelUserName = this.InputData.modelUserName;
                    } else {
                        this.$refs.child.isdisabledFn = false;
                        this.$refs.child.showSaveBtn = true;
                        let setselectionarr = [];
                        if (this.InputData.modelUser != null) {
                            let modelUser = this.InputData.modelUser.split(",");
                            let modelUserName = this.InputData.modelUserName.split(",");
                            for (let i = 0; i < modelUser.length; i++) {
                                setselectionarr.push({label: modelUserName[i], value: modelUser[i]});
                            }
                        }
                        this.$refs.child.setselectionarr = setselectionarr;
                        setTimeout(() => {
                            this.$refs.child.$refs.childConOrg.setCurrentOrg();
                        }, 100);
                    }
                    this.model1 = true;
                }).catch(e => {
                    this.$Message.error('请求失败' + e);
                })

            },
            query() {
                this.loading = true;
                let data = {
                    currentPage: this.pagedata.currentPage,
                    size: this.pagedata.pageSize,
                    userId: JSON.parse(sessionStorage('paramUserInfo').get('userInfo'))["createUserId"],
                }

                data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));

                let url = Api.getModelList;
                this.$http.get(url, {params: data}).then((res) => {
                    this.dataTable = res.data.data;
                    this.pagedata.total = res.data.totalSize;
                    this.loading = false;
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },
            reset() {
                this.form1 = {};
                this.$refs.childConOrg.resetCurrentOrg();
                this.query();
            },
            addOrUpdateData() {
                this.model1 = false;
                this.query();
            },
            batDelete() {
                let modelId = '';
                this.deleteRows.forEach(item => {
                    modelId = modelId + item.modelId + ";"
                });
                modelId = modelId.substring(0, modelId.length - 1);

                let url = Api.deleteModel;
                this.$http.get(url, {params: {modelId: modelId}}).then((res) => {
                    this.$Message.success('删除成功');
                    this.query()
                }).catch(e => {
                    this.$Message.error('请求失败' + e);
                })
            }
        }
    }
</script>
<style lang='css' scoped>
    @import './../../../../index.css';
</style>
